package com.xxrl.shop.service;

import com.xxrl.shop.domain.Cart;
import com.xxrl.shop.repository.CartRepository;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author mis
 */
@Service
public class CartService {

    private final CartRepository cartRepository;


    public CartService(CartRepository cartRepository) {
        this.cartRepository = cartRepository;
    }

    public void addCart(Cart cart) {
        cartRepository.save(cart);
    }

    public void updateCheck(Long userId, Boolean check) {
        Iterable<Cart> cartIterable = cartRepository.findAllByUserId(userId);
        for (Cart cart : cartIterable) {
            cart.setChecked(check);
        }
        cartRepository.saveAll(cartIterable);
    }

    public void saveCart(Long userId, Long productId, Boolean checked, Integer productNum) {
        Cart oldCart = cartRepository.findFirstByUserIdAndProductId(userId, productId);
        if (oldCart == null) {
            oldCart = new Cart();
            oldCart.setProductId(productId);
            oldCart.setUserId(userId);
        }
        oldCart.setChecked(checked);
        oldCart.setProductNum(productNum);
        cartRepository.save(oldCart);
    }


    public void deleteCart(Long userId, Long productId) {
        cartRepository.deleteByUserIdAndProductId(userId, productId);
    }

    public List<Cart> listCart(Long userId) {
        return cartRepository.findAllByUserId(userId);
    }


    public void deleteAllCart(Long userId) {
        cartRepository.deleteAllByUserId(userId);
    }
}
